'use strict';

/**
 * 门禁控制器指令发送
 */
const net = require('net');

let times = {};

let array2 = [0xf8, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x27, 0x22];
let array1 = [0xf8, 0x20, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x3c, 0x8d];

function openDoor(host, port, no) {
    port = port || 5768;
    no = no || '1:01';
    
    let key = host + port + no;
    console.log(key);
    const now = new Date().getTime();
    // 控制一下2s之内执行一次
    let lastTime = times[key];
    if (lastTime && (now - lastTime) < 2000) {
        console.log('LAST TIME: ' + (now - lastTime) + "ms");
        return;
    }
    console.log('host ', host, ' port ', port, ' no ', no);
    times[key] = new Date().getTime();

    const client = new net.Socket();
    const start = new Date().getTime();
    client.connect(port, host, function () {
        const end = new Date().getTime();
        console.log('CONNECTED TO: ' + host + ':' + port + ':' + no.split(':')[0] + ' ' + (end - start) + "ms");
        // 建立连接后立即向服务器发送数据，服务器将收到这些数据
        // 01表示1秒后off，最大99秒
        //
        //
        no = no.split(':');
        if (no.length > 0) {
            if (no[0] == '1') {
                client.write(Buffer.from(array1));
            } else {
                client.write(Buffer.from(array2));
            }
        }
        // 粗糙处理了，可能偶尔会有BUG

        setTimeout(function () {
            client.destroy();
        }, 1000);
    });

    // 为客户端添加“data”事件处理函数
    // data是服务器发回的数据
    client.on('data', function (data) {
        console.log('DATA: ' + data);
    });

    client.on('end', function () {
        console.log('client disconnected');
    });

    client.on('error', function (err) {
        console.log('socket error - ', err);
    });

    // 为客户端添加“close”事件处理函数
    client.on('close', function () {
        console.log('connection closed');
    });
}

exports.openDoor = openDoor;
